﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Web.Ajax.Data
{
	public class Cache<T> where T : class
	{
		public DateTime InsertTime=DateTime.Now;
		public TimeSpan Lifetime=new TimeSpan(0,0,0,0);

		private T Item;

		public bool IsValid()
		{
			return Item!=null && (InsertTime.Add(Lifetime) > DateTime.Now);
		}

		public T Get()
		{
			if (!IsValid())
				return null;
			return Item;
		}

		public delegate T GetDelegate();
		public T Get(GetDelegate d, TimeSpan? t)
		{
			var i = Get();
			if (i == null)
			{
				i = d();
				Set(i, (t??GetDefaultLifespan()));
			}
			return i;
		}

		public static TimeSpan GetDefaultLifespan()
		{
			return new TimeSpan(0, 0, 0, 0);
		}

		public void Set(T item, TimeSpan lifetime)
		{
			Item = item;
			InsertTime = DateTime.Now;
			Lifetime = lifetime;
		}

		public void Set(T item)
		{
			Set(item, GetDefaultLifespan()); 
		}

		public void Clear()
		{
			Item = null;
		}

	}
}
